
<template>
  <div class='repairRecord_container'>
    <el-card class="box-card">
      <div slot="header" class="card-header">
        <div class="header-left">
          <i class="fa fa-history"></i>
          <span>申请记录</span>
        </div>
        <div class="header-right">
          <el-input
            placeholder="搜索报修记录..."
            prefix-icon="el-icon-search"
            v-model="searchQuery"
            clearable
            @clear="handleSearchClear"
            @input="handleSearch">
          </el-input>
        </div>
      </div>

      <div class="filter-section">
        <div class="filter-title">
          <i class="fa fa-filter"></i>
          <span>状态筛选:</span>
        </div>
        <div class="filter-tags">
          <el-tag
            class="clear-filter"
            :class="{ 'active': selectedStatus === null }"
            @click="clearStatusFilter"
            effect="plain">
            全部
          </el-tag>
          <el-tag
            v-for="(status, index) in repairStatusFilters"
            :key="index"
            :class="{ 'active': selectedStatus === status.statusCode }"
            @click="toggleStatusFilter(status.statusCode)"
            :effect="selectedStatus === status.statusCode ? 'dark' : 'plain'">
            {{ status.statusValue }}
          </el-tag>
        </div>
      </div>
      
      <!-- 调试信息 -->
      <div v-if="showDebug" class="debug-info">
        <h3>调试信息 <el-button type="text" @click="showDebug = false">关闭</el-button></h3>
        <div class="debug-section">
          <h4>原始响应数据:</h4>
          <pre>{{ JSON.stringify(rawResponseData, null, 2) }}</pre>
        </div>
        <div class="debug-section">
          <h4>处理后的表格数据:</h4>
          <pre>{{ JSON.stringify(tableData, null, 2) }}</pre>
        </div>
        <div class="debug-section">
          <h4>申请材料列表:</h4>
          <pre>{{ JSON.stringify(applyMaterialList, null, 2) }}</pre>
        </div>
      </div>
      
      <!-- 错误提示 -->
      <div v-if="errorMessage" class="error-message">
        <i class="fa fa-exclamation-circle"></i>
        <span>{{ errorMessage }}</span>
        <div class="error-actions">
          <el-button type="primary" size="small" @click="retryLoad">
            <i class="fa fa-refresh"></i> 重试
          </el-button>
          <el-button type="info" size="small" @click="showDebug = !showDebug">
            <i class="fa fa-bug"></i> {{ showDebug ? '隐藏调试' : '显示调试' }}
          </el-button>
        </div>
      </div>

      <div class="table-wrapper">
        <el-table 
          :data="tableDataPaging"
          row-key="orderId"
          border 
          v-loading="tableDataLoading"
          element-loading-text="拼命加载中" 
          :header-cell-style="{background:'#F3F4F7',color:'#555'}"
          :default-sort="{prop: 'repairDate', order: 'descending'}" 
          @filter-change="filterTagTable"
          style="width: 100%">
          <el-table-column type="expand">
            <template #default="props">
              <div class="expanded-content">
                <div class="detail-row">
                  <div class="detail-item">
                    <div class="detail-icon"><i class="fa fa-map-marker"></i></div>
                    <div class="detail-content">
                      <span class="label">报修地址</span>
                      <span class="value">{{ props.row.repairAddress || '未提供' }}</span>
                    </div>
                  </div>
                  <div class="detail-item">
                    <div class="detail-icon"><i class="fa fa-phone"></i></div>
                    <div class="detail-content">
                      <span class="label">联系电话</span>
                      <span class="value">{{ props.row.repairPhone || '未提供' }}</span>
                    </div>
                  </div>
                </div>
                <div class="detail-row">
                  <div class="detail-item full-width">
                    <div class="detail-icon"><i class="fa fa-comment"></i></div>
                    <div class="detail-content">
                      <span class="label">报修问题</span>
                      <span class="value">{{ props.row.repairContent || '未提供详情' }}</span>
                    </div>
                  </div>
                </div>
                <div class="detail-row" v-if="props.row.imgUrl && props.row.imgUrl.length">
                  <div class="detail-item full-width">
                    <div class="detail-icon"><i class="fa fa-image"></i></div>
                    <div class="detail-content">
                      <span class="label">图片资料</span>
                      <div class="image-gallery">
                        <el-image 
                          v-for="(url, index) in props.row.imgUrl" 
                          :key="index"
                          :src="url"
                          :preview-src-list="props.row.imgUrl">
                        </el-image>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column type="index" align="center" width="60" :index="tableIndex">
          </el-table-column>
          
          <el-table-column align="center" prop="orderId" label="单号" width="180">
            <template #default="scope">
              <div class="order-id">
                <span class="id-text">#{{ scope.row.orderId || '未知' }}</span>
                <el-tooltip content="复制单号" placement="top" effect="light">
                  <i class="fa fa-copy copy-icon" @click="copyOrderId(scope.row.orderId)"></i>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column align="center" prop="repairTypeEntity.typeValue" label="报修类型" width="150">
            <template #default="scope">
              <el-tag size="small" effect="plain">
                {{ scope.row.repairTypeEntity && scope.row.repairTypeEntity.typeValue ? scope.row.repairTypeEntity.typeValue : '未分类' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column align="center" prop="repairStatusEntity.statusValue" label="报修状态" width="150">
            <template #default="scope">
              <div class="status-cell">
                <el-tooltip v-if="scope.row.rejectReason" :content="'原因: ' + scope.row.rejectReason" placement="top" effect="light">
                  <el-tag :type="getStatusType(scope.row)" effect="light" class="status-tag">
                    <i :class="getStatusIcon(scope.row.statusCode)"></i>
                    {{ scope.row.statusCode === 3 ? '已完结' : (scope.row.statusCode === 5 ? '待完结' : (scope.row.repairStatusEntity && scope.row.repairStatusEntity.statusValue ? scope.row.repairStatusEntity.statusValue : '未知状态')) }}
                  </el-tag>
                </el-tooltip>
                <el-tag v-else :type="getStatusType(scope.row)" effect="light" class="status-tag">
                  <i :class="getStatusIcon(scope.row.statusCode)"></i>
                  {{ scope.row.statusCode === 3 ? '已完结' : (scope.row.statusCode === 5 ? '待完结' : (scope.row.repairStatusEntity && scope.row.repairStatusEntity.statusValue ? scope.row.repairStatusEntity.statusValue : '未知状态')) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column align="center" prop="repairDate" label="报修时间" width="180" sortable>
            <template #default="scope">
              <div class="time-cell">
                <div class="date">{{ formatDate(scope.row.repairDate, 'date') }}</div>
                <div class="time">{{ formatDate(scope.row.repairDate, 'time') }}</div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column align="center" prop="workerEntity.workerName" label="维修工" width="150">
            <template #default="scope">
              <div class="worker-cell" v-if="scope.row.workerEntity && scope.row.workerEntity.workerName">
                <el-avatar :size="24" class="worker-avatar">
                  {{ scope.row.workerEntity.workerName.charAt(0) }}
                </el-avatar>
                <span class="worker-name">{{ scope.row.workerEntity.workerName }}</span>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <el-table-column align="center" fixed="right" label="操作" width="150" v-if="tableDataPaging.length !== 0">
            <template #default="scope">
              <div class="action-cell">
                <el-popconfirm
                  v-if="scope.row.statusCode === 1"
                  title="确定要取消此报修申请吗？"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-warning"
                  icon-color="#ff4949"
                  @confirm="cancelOrder(scope.row)">
                  <template #reference>
                    <el-button type="danger" size="small">
                      <i class="fa fa-times"></i>
                      取消申请
                    </el-button>
                  </template>
                </el-popconfirm>
                
                <el-button
                  v-else-if="handlerWaitChargeBtnShow(scope.row.orderId)"
                  :type="['danger','success'].at(handlerWaitChargeBtnShowText(scope.row.orderId))"
                  size="small"
                  @click="chargeOn(scope.row.orderId, scope.row)">
                  <i :class="handlerWaitChargeBtnShowText(scope.row.orderId) ? 'fa fa-check' : 'fa fa-credit-card'"></i>
                  {{ ['待缴费','已缴费'].at(handlerWaitChargeBtnShowText(scope.row.orderId)) }}
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="pagination">
        <el-pagination
          @size-change="val=>pagination.pageSize = val"
          @current-change="val=>pagination.currentPage = val"
          :current-page="pagination.currentPage"
          :pager-count="pagination.pagerCount"
          :page-sizes="pagination.pageSizes"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          background>
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { useMainStore } from '@/js/store.js'
import { imgUrlAddress, repairStatusStyle } from '@/js/public.js'
import jsmd5 from 'js-md5'
import dayjs from 'dayjs'
import axios from '@/js/axios.js'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { ref, onMounted } from 'vue'

export default {
  setup() {
    const router = useRouter();
    const isLoading = ref(false);
    
    onMounted(() => {
      console.log('报修记录组件已挂载');
    });
    
    return { router, isLoading };
  },
  data() {
    return {
      store: useMainStore(),
      tableData: [],
      tableDataLoading: true,
      tableDataF: [],
      searchQuery: '',
      selectedStatus: null, // 改为单选，初始值为null表示不筛选
      pagination: {
        pageSize: 10,
        pageSizes: [10, 50, 100, 200],
        pagerCount: 5,
        currentPage: 1,
        total: 0,
      },
      queryList: {
        aStatus: []
      },
      repairStatusStyle,
      chargeStatus: {},
      errorMessage: '',
      applyMaterialList: [],
      showDebug: false,
      rawResponseData: null,
    }
  },
  computed: {
    tableDataPaging() {
      try {
        let filteredData = this.tableData || [];
        
        // 搜索过滤
        if (this.searchQuery) {
          const query = this.searchQuery.toLowerCase();
          filteredData = filteredData.filter(item => {
            if (!item) return false;
            
            return (
              (item.orderId && item.orderId.toLowerCase().includes(query)) ||
              (item.repairAddress && item.repairAddress.toLowerCase().includes(query)) ||
              (item.repairContent && item.repairContent.toLowerCase().includes(query)) ||
              (item.workerEntity && item.workerEntity.workerName && 
                item.workerEntity.workerName.toLowerCase().includes(query))
            );
          });
        }
        
        // 状态过滤 - 修改为使用statusCode进行过滤
        if (this.selectedStatus !== null) {
          filteredData = filteredData.filter(item => {
            return item && item.statusCode === this.selectedStatus;
          });
        }
        
        const { currentPage, pageSize } = this.pagination;
        this.pagination.total = filteredData.length;
        const pagedData = filteredData.slice((currentPage - 1) * pageSize, currentPage * pageSize);
        
        // 打印分页后的数据
        console.log(`📄 当前页数据 (第${currentPage}页):`, pagedData.map(item => ({
          orderId: item.orderId,
          statusCode: item.statusCode
        })));
        
        return pagedData;
      } catch (error) {
        console.error('计算表格数据时出错:', error);
        this.errorMessage = '数据处理出错，请刷新页面重试';
        return [];
      }
    },
    
    // 修复状态过滤器，确保显示正确的状态文字
    repairStatusFilters() {
      try {
        // 如果后端没有返回状态数据，则使用默认状态
        if (!this.store.repairStatus || this.store.repairStatus.length === 0) {
          return [
            { statusCode: 1, statusValue: "待接单" },
            { statusCode: 2, statusValue: "已接单" },
            { statusCode: 3, statusValue: "维修中" },
            { statusCode: 4, statusValue: "待付款" },
            { statusCode: 5, statusValue: "待完结" }, // 修改为"待完结"
            { statusCode: 6, statusValue: "已取消" }
          ];
        }
        
        return this.store.repairStatus.filter(item => item && item.statusCode);
      } catch (error) {
        console.error('获取状态过滤器时出错:', error);
        return [];
      }
    }
  },
  methods: {
    // 新增方法
    handleSearch() {
      this.pagination.currentPage = 1;
    },
    
    handleSearchClear() {
      this.searchQuery = '';
      this.handleSearch();
    },
    
    // 修改状态过滤方法，改为单选
    toggleStatusFilter(statusCode) {
      if (this.selectedStatus === statusCode) {
        // 如果点击的是已选中的状态，则取消选择
        this.selectedStatus = null;
      } else {
        // 否则选中点击的状态
        this.selectedStatus = statusCode;
      }
      this.pagination.currentPage = 1;
    },
    
    // 添加清除筛选方法
    clearStatusFilter() {
      this.selectedStatus = null;
      this.pagination.currentPage = 1;
    },
    
    formatDate(dateStr, type) {
      if (!dateStr) return '-';
      const date = dayjs(dateStr);
      if (type === 'date') {
        return date.format('YYYY-MM-DD');
      } else {
        return date.format('HH:mm:ss');
      }
    },
    
    // 修改状态图标映射
    getStatusIcon(statusCode) {
      const iconMap = {
        1: 'fa fa-clock-o',
        2: 'fa fa-user-circle',
        3: 'fa fa-wrench',
        4: 'fa fa-credit-card',
        5: 'fa fa-hourglass-half', // 修改状态5的图标为沙漏
        6: 'fa fa-times-circle'
      };
      return iconMap[statusCode] || 'fa fa-question-circle';
    },
    
    // 修改状态类型映射
    getStatusType(row) {
      if (!row || !row.statusCode) return '';
      
      const statusMap = {
        1: 'info',    // 待接单
        2: 'warning', // 已接单
        3: 'primary', // 维修中
        4: 'danger',  // 待付款
        5: 'warning', // 待完结
        6: 'danger'   // 已取消
      };
      
      return statusMap[row.statusCode] || '';
    },
    
    copyOrderId(orderId) {
      navigator.clipboard.writeText(orderId).then(() => {
        ElMessage.success('单号已复制到剪贴板');
      }).catch(() => {
        ElMessage.error('复制失败，请手动复制');
      });
    },
    
    tableIndex(index) {
      return (this.pagination.currentPage - 1) * this.pagination.pageSize + index + 1;
    },
    
    handlerWaitChargeBtnShow(orderId) {
      return this.tableData.find(item => item.orderId === orderId && item.statusCode === 4) !== undefined;
    },
    
    handlerWaitChargeBtnShowText(orderId) {
      return this.chargeStatus[orderId] ? 1 : 0;
    },
    
    chargeOn(orderId, rowData) {
      console.log('===== 点击事件调试 =====');
      console.log('传入的orderId参数:', orderId);
      console.log('传入的rowData参数:', rowData);
      console.log('rowData.orderId:', rowData?.orderId);
      console.log('两者是否相等:', orderId === rowData?.orderId);
      console.log('========================');
      
      // 修复：直接使用rowData中的orderId，避免scope绑定错误
      const actualOrderId = rowData?.orderId || orderId;
      
      if (!actualOrderId) {
        ElMessage.error('订单ID获取失败，请刷新页面重试');
        console.error('orderId和rowData.orderId都为空！');
        return;
      }
      
      if (this.chargeStatus[actualOrderId]) {
        ElMessage.info('已完成支付');
        return;
      }
      
      // 调试信息：显示store中的数据
      console.log('===== 调试信息 =====');
      console.log('实际使用的订单ID:', actualOrderId, '类型:', typeof actualOrderId);
      console.log('store.waitPayOrders:', this.store.waitPayOrders);
      console.log('store.waitPayOrders 是否存在:', !!this.store.waitPayOrders);
      console.log('store.waitPayOrders 长度:', this.store.waitPayOrders ? this.store.waitPayOrders.length : 0);
      
      // 输出每个item的orderId用于对比
      if (this.store.waitPayOrders) {
        this.store.waitPayOrders.forEach((item, index) => {
          console.log(`[${index}] orderId:`, item.orderId, '类型:', typeof item.orderId);
          console.log(`  比较: "${item.orderId}" == "${actualOrderId}"`, item.orderId == actualOrderId);
          console.log(`  严格比较: "${item.orderId}" === "${actualOrderId}"`, item.orderId === actualOrderId);
          console.log(`  长度: ${item.orderId?.length} vs ${actualOrderId?.length}`);
          console.log(`  JSON: ${JSON.stringify(item.orderId)} vs ${JSON.stringify(actualOrderId)}`);
        });
      }
      
      // 先获取该订单的待付款材料列表（使用宽松相等 == 避免类型不匹配）
      const orderMaterials = this.store.waitPayOrders ? this.store.waitPayOrders.filter(item => item.orderId == actualOrderId) : [];
      
      console.log('筛选出的订单材料:', orderMaterials);
      console.log('==================');
      
      if (!orderMaterials || orderMaterials.length === 0) {
        ElMessage.error('未找到待付款的订单信息，请刷新页面重试');
        console.error('store.waitPayOrders 为空或不包含该订单的数据');
        console.error('请检查：1. 后端是否返回了数据 2. 前端是否保存到store 3. 是否重启了前端服务');
        return;
      }
      
      // 提取所有applyId
      const applyIds = orderMaterials.map(item => item.applyId);
      const time = new Date().getTime();
      
      // 生成MD5签名
      const md5Str = JSON.stringify(applyIds) + '/userHome/getPayHashCode' + time;
      const md5ApplyId = jsmd5(md5Str);
      
      // 调用后端接口获取凭证码
      axios.post('/userHome/getPayHashCode', {
        applyIds: applyIds,
        md5ApplyId: md5ApplyId,
        time: time
      }).then(res => {
        if (res.data.code === 43000 || res.data.code === 200) {
          // 将凭证码存储到localStorage
          const code = res.data.data;
          localStorage.setItem(actualOrderId, code);
          console.log('已生成凭证码:', code, '订单ID:', actualOrderId);
          
          // 跳转到支付页面（注意：路由是 charge_on 不是 chargeOn）
          this.router.push({
            path: '/userHome/charge_on',
            query: {
              orderId: actualOrderId
            }
          });
        } else {
          ElMessage.error(res.data.msg || '获取支付凭证失败');
        }
      }).catch(err => {
        console.error('获取支付凭证失败:', err);
        ElMessage.error('网络错误，请稍后再试');
      });
    },
    
    cancelOrder(row) {
      axios.post('/userHome/cancelOrder', {
        orderId: row.orderId,
        statusCode: row.statusCode
      }).then(res => {
        if (res.data.code === 43000) {  // 修复：使用正确的成功状态码
          ElMessage.success(res.data.msg || '取消成功');
          this.getRepairRecord();  // 刷新列表数据
        } else {
          ElMessage.error(res.data.msg || '取消失败');
        }
      }).catch(err => {
        ElMessage.error('网络错误，请稍后再试');
        console.error(err);
      });
    },
    
    getRepairRecord() {
      this.tableDataLoading = true;
      this.errorMessage = '';
      
      try {
        console.log('开始获取报修记录...');
        axios.get('/userHome/queryUserOrderRecord').then(res => {
          // 保存原始响应数据用于调试
          this.rawResponseData = res.data;
          
          // 添加调试信息，查看返回的完整数据结构
          console.log('获取报修记录返回数据:', JSON.stringify(res.data, null, 2));
          
          if (res.data.code === 200 || res.data.code === 43000) { // 添加43000作为成功码
            // 处理订单数据，根据控制台显示的实际数据结构进行调整
            let orderData = [];
            
            // 检查数据结构，适配不同的返回格式
            if (res.data.data && typeof res.data.data === 'object') {
              console.log('数据类型:', Array.isArray(res.data.data) ? '数组' : '对象');
              console.log('数据键:', Object.keys(res.data.data));
              
              if (Array.isArray(res.data.data)) {
                // 如果是数组，直接使用
                orderData = res.data.data;
                console.log('使用数组数据');
              } else if (res.data.data.orderFormEntityList) {
                // 如果有orderFormEntityList字段
                orderData = res.data.data.orderFormEntityList;
                console.log('使用orderFormEntityList数据');
                
                // 同时保存待付款订单数据到store，供chargeOn.vue使用
                if (res.data.data.applyMaterialEntityList) {
                  this.store.waitPayOrders = res.data.data.applyMaterialEntityList;
                  console.log('已保存待付款订单数据到store:', this.store.waitPayOrders);
                  
                  // 调试：对比两个列表的orderId
                  console.log('📋 订单列表中的订单ID:');
                  orderData.forEach((order, idx) => {
                    console.log(`  [${idx}] ${order.orderId} (状态: ${order.statusCode})`);
                  });
                  console.log('📦 材料列表中的订单ID:');
                  res.data.data.applyMaterialEntityList.forEach((material, idx) => {
                    console.log(`  [${idx}] ${material.orderId} (applyId: ${material.applyId})`);
                  });
                }
              } else if (res.data.data.applyMaterialEntityList && !orderData.length) {
                // 如果只有applyMaterialEntityList字段
                this.applyMaterialList = res.data.data.applyMaterialEntityList || [];
                // 同时保存到store
                this.store.waitPayOrders = this.applyMaterialList;
                
                // 从applyMaterialEntityList中提取订单信息
                const uniqueOrderIds = new Set();
                const orderMap = {};
                
                // 修改从applyMaterialEntityList提取订单信息时的状态映射
                this.applyMaterialList.forEach(item => {
                  if (item.orderId && !uniqueOrderIds.has(item.orderId)) {
                    uniqueOrderIds.add(item.orderId);
                    
                    // 创建基本订单对象
                    orderMap[item.orderId] = {
                      orderId: item.orderId,
                      repairContent: item.materialName || '材料申请',
                      repairDate: item.createTime || '',
                      statusCode: item.isPay ? 5 : 4, // 修正状态码：5=待完结，4=待付款
                      repairTypeEntity: { typeValue: '材料申请' },
                      repairStatusEntity: { 
                        statusValue: item.isPay ? '待完结' : '待付款', // 修正状态文字
                        statusCode: item.isPay ? 5 : 4 // 修正状态码
                      },
                      repairAddress: '未知',
                      repairPhone: '未知'
                    };
                  }
                });
                
                // 转换为数组
                orderData = Object.values(orderMap);
                console.log('从applyMaterialEntityList提取的订单数据:', orderData);
              } else {
                // 尝试直接使用data对象
                const dataKeys = Object.keys(res.data.data);
                console.log('尝试处理其他数据结构，键:', dataKeys);
                
                if (dataKeys.length > 0) {
                  // 检查是否有订单相关字段
                  const hasOrderData = dataKeys.some(key => 
                    key.toLowerCase().includes('order') || 
                    key.toLowerCase().includes('repair')
                  );
                  
                  if (hasOrderData) {
                    orderData = [res.data.data];
                  } else {
                    console.log('数据结构中没有找到订单相关字段');
                    this.errorMessage = '没有找到报修记录数据';
                  }
                }
              }
            }
            
            console.log('处理后的订单数据:', orderData);
            console.log('订单数据长度:', orderData.length);
            
            // 处理订单数据
            this.tableData = (orderData || []).map(item => {
              if (!item) return {};
              
              // 添加调试信息
              console.log('处理订单项:', item);
              
              // 确保必要的字段存在
              const processedItem = {
                ...item,
                orderId: item.orderId || '',
                repairAddress: item.repairAddress || '',
                repairPhone: item.repairPhone || '',
                repairContent: item.repairContent || '',
                repairDate: item.repairDate || '',
                statusCode: item.statusCode || 0,
                repairTypeEntity: item.repairTypeEntity || { typeValue: '未知' },
                repairStatusEntity: item.repairStatusEntity || { statusValue: '未知' },
                workerEntity: item.workerEntity || null
              };
              
              // 修正状态文字显示
              if (processedItem.statusCode === 3 && processedItem.repairStatusEntity) {
                processedItem.repairStatusEntity.statusValue = "维修中";
              }
              if (processedItem.statusCode === 5 && processedItem.repairStatusEntity) {
                processedItem.repairStatusEntity.statusValue = "待完结";
              }
              
              // 处理图片URL
              if (item.imgUrl) {
                try {
                  // 使用imgUrlAddress函数处理图片URL
                  processedItem.imgUrl = imgUrlAddress(item.imgUrl);
                } catch (e) {
                  console.error('处理图片URL时出错:', e);
                  processedItem.imgUrl = [];
                }
              } else {
                processedItem.imgUrl = [];
              }
              
              return processedItem;
            });
            
            console.log('最终表格数据:', this.tableData);
            
            // 打印每条记录的关键信息用于调试
            console.log('🔍 最终tableData中的订单列表:');
            this.tableData.forEach((item, idx) => {
              console.log(`  [${idx}] orderId=${item.orderId}, statusCode=${item.statusCode}`);
            });
            
            // 更新分页信息
            this.pagination.total = this.tableData.length;
            
            // 检查是否有已缴费的订单
            this.checkChargeStatus();
            
            // 如果没有数据，显示提示
            if (this.tableData.length === 0) {
              this.errorMessage = '暂无报修记录';
            }
          } else {
            ElMessage.error(res.data.msg || '获取报修记录失败');
            this.errorMessage = res.data.msg || '获取报修记录失败';
          }
          this.tableDataLoading = false;
        }).catch(err => {
          ElMessage.error('网络错误，请稍后再试');
          console.error('获取报修记录网络错误:', err);
          this.errorMessage = '网络错误，请稍后再试';
          this.tableDataLoading = false;
        });
      } catch (error) {
        console.error('获取报修记录时发生异常:', error);
        this.errorMessage = '系统错误，请刷新页面重试';
        this.tableDataLoading = false;
      }
    },
    
    checkChargeStatus() {
      // 获取需要缴费的订单ID列表
      const chargeOrderIds = this.tableData
        .filter(item => item.statusCode === 4)
        .map(item => item.orderId);
      
      if (chargeOrderIds.length === 0) return;
      
      // 查询缴费状态 - 使用applyMaterialEntityList来判断
      try {
        // 从已获取的数据中判断缴费状态
        if (this.applyMaterialList && this.applyMaterialList.length > 0) {
          this.applyMaterialList.forEach(item => {
            if (item.orderId && item.isPay) {
              this.chargeStatus[item.orderId] = true;
            }
          });
        }
      } catch (err) {
        console.error('处理缴费状态失败', err);
      }
    },
    
    // 获取报修状态
    getRepairStatus() {
      axios.get('/userHome/repairStatus').then(res => {
        if (res.data.code === 200 || res.data.code === 43000) {
          console.log('获取到报修状态数据:', res.data.data);
          
          // 状态映射已由后端统一管理，直接使用后端返回的状态
          this.store.repairStatus = res.data.data;
        } else {
          console.error('获取报修状态失败:', res.data.msg);
          // 设置静态报修状态数据作为备用，确保与数据库状态一致
          this.store.repairStatus = [
            { statusCode: 1, statusValue: "待接单" },
            { statusCode: 2, statusValue: "已接单" },
            { statusCode: 3, statusValue: "维修中" },
            { statusCode: 4, statusValue: "待付款" },
            { statusCode: 5, statusValue: "待完结" },
            { statusCode: 6, statusValue: "已取消" },
            { statusCode: 7, statusValue: "已完结" }
          ];
        }
      }).catch(err => {
        console.error('获取报修状态网络错误:', err);
        // 设置静态报修状态数据作为备用，确保与数据库状态一致
        this.store.repairStatus = [
          { statusCode: 1, statusValue: "待接单" },
          { statusCode: 2, statusValue: "已接单" },
          { statusCode: 3, statusValue: "维修中" },
          { statusCode: 4, statusValue: "待付款" },
          { statusCode: 5, statusValue: "待完结" },
          { statusCode: 6, statusValue: "已取消" },
          { statusCode: 7, statusValue: "已完结" }
        ];
      });
    },
    
    filterTagTable(filters) {
      this.queryList.aStatus = filters.status || [];
    },
    
    retryLoad() {
      this.errorMessage = '';
      this.getRepairStatus();
      this.getRepairRecord();
    },

    getStatusType(row) {
      if (!row || !row.statusCode) return '';
      
      const statusMap = {
        1: 'info',    // 待接单
        2: 'warning', // 已接单
        3: 'primary', // 维修中
        4: 'danger',  // 待付款
        5: 'warning', // 待完结
        6: 'danger',  // 已取消
        7: 'success'  // 已完结
      };
      
      return statusMap[row.statusCode] || '';
    }
  },
  created() {
    try {
      // 确保报修状态已加载
      if (!this.store.repairStatus || this.store.repairStatus.length === 0) {
        this.getRepairStatus();
      }
      
      // 获取报修记录
      this.getRepairRecord();
    } catch (error) {
      console.error('组件初始化时出错:', error);
      this.errorMessage = '初始化失败，请刷新页面重试';
    }
  },
  
  // 组件被keep-alive缓存后，每次激活时都会调用此钩子
  activated() {
    console.log('报修记录页面被激活，重新获取数据');
    try {
      // 每次页面激活时重新获取报修记录
      this.getRepairRecord();
    } catch (error) {
      console.error('页面激活时获取数据出错:', error);
      this.errorMessage = '获取数据失败，请刷新页面重试';
    }
  }
}
</script>

<style lang="scss" scoped>
.repairRecord_container {
  padding: 5px;
  max-height: calc(100vh - 80px);
  display: flex;
  flex-direction: column;
  
  .box-card {
    border-radius: 16px;
    overflow: hidden;
    transition: all 0.3s;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
    border: none;
    background: #fff;
    display: flex;
    flex-direction: column;
    height: 100%;
    
    &:hover {
      box-shadow: 0 15px 40px rgba(79, 172, 254, 0.15);
    }
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      padding: 10px 15px;
      position: relative;
      overflow: hidden;
      
      &::before {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 60%);
        animation: ripple 15s infinite linear;
      }
      
      @keyframes ripple {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
      }
      
      .header-left {
        display: flex;
        align-items: center;
        gap: 15px;
        position: relative;
        z-index: 2;
        
        i {
          font-size: 24px;
          color: #fff;
          animation: rotate 10s linear infinite;
          background: rgba(255, 255, 255, 0.2);
          width: 40px;
          height: 40px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
        
        @keyframes rotate {
          from { transform: rotate(0deg); }
          to { transform: rotate(360deg); }
        }
        
        span {
          color: #fff;
          font-size: 20px;
          font-weight: 600;
          letter-spacing: 1px;
          text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
      }
      
      .header-right {
        position: relative;
        z-index: 2;
        
        :deep(.el-input) {
          width: 250px;
          
          .el-input__wrapper {
            border-radius: 30px;
            background: rgba(255, 255, 255, 0.15);
            box-shadow: none;
            border: 1px solid rgba(255, 255, 255, 0.3);
            padding: 6px 12px;
            backdrop-filter: blur(5px);
            
            input {
              color: #fff;
              font-size: 14px;
              
              &::placeholder {
                color: rgba(255, 255, 255, 0.7);
              }
            }
            
            .el-input__prefix {
              color: rgba(255, 255, 255, 0.8);
              font-size: 16px;
              margin-right: 8px;
            }
          }
        }
      }
    }
    
    .filter-section {
      display: flex;
      padding: 10px 15px;
      border-bottom: 1px solid #edf2f7;
      background: #f8fafc;
      position: relative;
      
      .filter-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-right: 15px;
        
        i {
          color: #4facfe;
          font-size: 16px;
        }
        
        span {
          color: #2d3748;
          font-weight: 600;
          font-size: 14px;
        }
      }
      
      .filter-tags {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        flex: 1;
      }
      
      .el-tag {
        cursor: pointer;
        padding: 6px 12px;
        border-radius: 20px;
        font-weight: 500;
        transition: all 0.3s;
        font-size: 12px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
        }
        
        &:not(.active) {
          &:hover {
            background: rgba(79, 172, 254, 0.1);
            color: #4facfe;
          }
        }
        
        &.active {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          color: white;
          border: none;
          animation: pulse 1.5s infinite;
        }
        
        @keyframes pulse {
          0% {
            box-shadow: 0 0 0 0 rgba(79, 172, 254, 0.4);
          }
          70% {
            box-shadow: 0 0 0 10px rgba(79, 172, 254, 0);
          }
          100% {
            box-shadow: 0 0 0 0 rgba(79, 172, 254, 0);
          }
        }

        &.clear-filter {
          background-color: #f0f2f5;
          
          &.active {
            background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
            color: white;
            border: none;
          }
        }
      }
    }
    
    .error-message {
      display: flex;
      align-items: center;
      margin: 15px 20px 0;
      padding: 12px 15px;
      background-color: #fff2f0;
      border: 1px solid #ffccc7;
      border-radius: 12px;
      color: #ff4d4f;
      
      i {
        font-size: 18px;
        margin-right: 10px;
      }
      
      span {
        flex: 1;
        font-size: 14px;
      }
      
      .error-actions {
        display: flex;
        gap: 10px;
      }
    }
    
    .debug-info {
      margin: 15px 20px 0;
      padding: 12px 15px;
      background-color: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 12px;
      
      h3 {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 0;
        margin-bottom: 10px;
        color: #2d3748;
        font-size: 16px;
        
        .el-button {
          font-size: 12px;
        }
      }
      
      .debug-section {
        margin-bottom: 10px;
        
        h4 {
          margin: 8px 0;
          color: #4a5568;
          font-size: 14px;
        }
        
        pre {
          padding: 8px;
          background-color: #edf2f7;
          border-radius: 6px;
          overflow: auto;
          max-height: 150px;
          font-family: monospace;
          font-size: 11px;
          color: #2d3748;
          white-space: pre-wrap;
        }
      }
    }
    
    .table-wrapper {
      flex: 1;
      overflow: auto;
      padding: 15px;
      max-height: calc(100vh - 250px);
      
      :deep(.el-table) {
        border-radius: 12px;
        overflow: hidden;
        border: 1px solid #edf2f7;
        box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
        
        // 表格样式增强
        .el-table__header {
          th {
            background: #f3f6fd !important;
            color: #2d3748 !important;
            font-weight: 600;
            font-size: 13px;
            padding: 8px 0;
            border-bottom: 1px solid #edf2f7;
            text-transform: uppercase;
            letter-spacing: 0.5px;
          }
        }
        
        .el-table__body {
          td {
            padding: 6px 0;
            font-size: 12px;
            color: #4a5568;
            border-bottom: 1px solid #edf2f7;
          }
          
          tr {
            transition: all 0.3s;
            
            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
              z-index: 1;
              
              td {
                background-color: #f8fafc !important;
              }
            }
          }
        }
        
        // 展开行样式
        .expanded-content {
          padding: 10px;
          background: #f8fafc;
          
          .detail-row {
            display: flex;
            gap: 20px;
            margin-bottom: 15px;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .detail-item {
              flex: 1;
              display: flex;
              gap: 12px;
              background: #fff;
              padding: 15px;
              border-radius: 12px;
              box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
              transition: all 0.3s;
              
              &:hover {
                transform: translateY(-2px);
                box-shadow: 0 8px 20px rgba(79, 172, 254, 0.15);
              }
              
              &.full-width {
                flex: 0 0 100%;
              }
              
              .detail-icon {
                width: 40px;
                height: 40px;
                background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
                border-radius: 10px;
                display: flex;
                align-items: center;
                justify-content: center;
                
                i {
                  font-size: 18px;
                  color: #fff;
                }
              }
              
              .detail-content {
                flex: 1;
                
                .label {
                  color: #64748b;
                  font-size: 12px;
                  margin-bottom: 5px;
                  display: block;
                  font-weight: 500;
                }
                
                .value {
                  color: #2d3748;
                  font-size: 14px;
                  font-weight: 500;
                  line-height: 1.5;
                }
                
                .image-gallery {
                  display: flex;
                  gap: 10px;
                  flex-wrap: wrap;
                  margin-top: 10px;
                  
                  .el-image {
                    width: 80px;
                    height: 80px;
                    border-radius: 8px;
                    overflow: hidden;
                    transition: all 0.3s;
                    border: 2px solid #fff;
                    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
                    
                    &:hover {
                      transform: scale(1.05) rotate(2deg);
                      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
                      z-index: 1;
                    }
                  }
                }
              }
            }
          }
        }
        
        // 单元格样式优化
        .order-id {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          
          .id-text {
            font-family: 'Roboto Mono', monospace;
            color: #2d3748;
            font-weight: 500;
            letter-spacing: 0.5px;
            font-size: 12px;
          }
          
          .copy-icon {
            color: #a0aec0;
            cursor: pointer;
            transition: all 0.2s;
            background: #f1f5f9;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 4px;
            
            &:hover {
              color: #fff;
              background: #4facfe;
              transform: scale(1.1);
            }
          }
        }
        
        .status-cell {
          .status-tag {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            border-radius: 20px;
            position: relative;
            overflow: hidden;
            font-weight: 500;
            font-size: 12px;
            
            i {
              font-size: 14px;
            }
            
            &::before {
              content: '';
              position: absolute;
              top: 0;
              left: -100%;
              width: 100%;
              height: 100%;
              background: linear-gradient(
                90deg,
                rgba(255, 255, 255, 0) 0%,
                rgba(255, 255, 255, 0.3) 50%,
                rgba(255, 255, 255, 0) 100%
              );
              animation: shimmer 2s infinite;
            }
            
            @keyframes shimmer {
              to {
                left: 100%;
              }
            }
          }
        }
        
        .time-cell {
          .date {
            color: #2d3748;
            font-weight: 600;
            margin-bottom: 0;
            font-size: 12px;
          }
          
          .time {
            color: #64748b;
            font-size: 11px;
          }
        }
        
        .worker-cell {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          
          .worker-avatar {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            font-size: 12px;
            box-shadow: 0 3px 10px rgba(79, 172, 254, 0.3);
          }
          
          .worker-name {
            color: #2d3748;
            font-weight: 500;
            font-size: 13px;
          }
        }
        
        .action-cell {
          .el-button {
            border-radius: 20px;
            padding: 4px 10px;
            font-weight: 500;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
            transition: all 0.3s;
            font-size: 12px;
            
            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            }
            
            i {
              margin-right: 3px;
            }
          }
        }
      }
    }
    
    .pagination {
      display: flex;
      justify-content: center;
      padding: 15px 10px;
      border-top: 1px solid #edf2f7;
      background-color: #fff;
      margin-top: auto;
      flex-shrink: 0;
      min-height: 60px;
      align-items: center;
      
      :deep(.el-pagination) {
        padding: 0;
        font-size: 12px;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 8px;
        
        .btn-prev, .btn-next {
          border-radius: 8px;
          background: #fff;
          border: 1px solid #e2e8f0;
          transition: all 0.3s;
          min-width: 32px;
          height: 32px;
          line-height: 32px;
          
          &:hover {
            color: #fff;
            background: #4facfe;
            border-color: #4facfe;
            transform: translateY(-2px);
            box-shadow: 0 3px 10px rgba(79, 172, 254, 0.3);
          }
        }
        
        .el-pager {
          li {
            border-radius: 8px;
            font-weight: 500;
            border: 1px solid #e2e8f0;
            margin: 0 2px;
            transition: all 0.3s;
            min-width: 32px;
            height: 32px;
            line-height: 32px;
            
            &:not(.active):hover {
              transform: translateY(-2px);
              box-shadow: 0 3px 10px rgba(79, 172, 254, 0.2);
              border-color: #4facfe;
              color: #4facfe;
            }
            
            &.active {
              background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
              color: white;
              border: none;
              transform: scale(1.1);
              box-shadow: 0 5px 15px rgba(79, 172, 254, 0.3);
            }
          }
        }
        
        .el-pagination__sizes {
          .el-select .el-input .el-input__wrapper {
            border-radius: 8px;
            height: 32px;
            line-height: 32px;
            
            &:hover {
              border-color: #4facfe;
            }
          }
        }
        
        .el-pagination__jump {
          .el-input .el-input__wrapper {
            border-radius: 8px;
            height: 32px;
            line-height: 32px;
            width: 50px;
            
            &:hover {
              border-color: #4facfe;
            }
          }
        }
        
        .el-pagination__total {
          font-weight: 500;
          color: #64748b;
        }
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .repairRecord_container {
    padding: 3px;
    max-height: calc(100vh - 60px);
    
    .box-card {
      border-radius: 12px;
      
      .card-header {
        padding: 8px 12px;
        flex-direction: column;
        gap: 8px;
        
        .header-left {
          width: 100%;
          justify-content: center;
        }
        
        .header-right {
          width: 100%;
          
          :deep(.el-input) {
            width: 100%;
          }
        }
      }
      
      .filter-section {
        padding: 8px 12px;
        flex-direction: column;
        gap: 8px;
        
        .filter-title {
          justify-content: center;
        }
        
        .filter-tags {
          justify-content: center;
          flex-wrap: wrap;
        }
        
        .el-tag {
          padding: 6px 12px;
          font-size: 12px;
          margin: 2px;
        }
      }
      
      .table-wrapper {
        padding: 8px;
        max-height: calc(100vh - 300px);
        
        :deep(.el-table) {
          .expanded-content {
            padding: 8px;
            
            .detail-row {
              flex-direction: column;
              gap: 8px;
            }
          }
        }
      }
      
      .pagination {
        padding: 10px 8px;
        min-height: 80px;
        
        :deep(.el-pagination) {
          font-size: 11px;
          justify-content: center;
          flex-wrap: wrap;
          gap: 4px;
          
          .el-pagination__total {
            order: -1;
            width: 100%;
            text-align: center;
            margin-bottom: 8px;
            font-size: 12px;
          }
          
          .el-pagination__sizes {
            order: 1;
            
            .el-select .el-input .el-input__wrapper {
              height: 28px;
              font-size: 11px;
            }
          }
          
          .btn-prev, .btn-next {
            min-width: 28px;
            height: 28px;
            line-height: 28px;
            font-size: 11px;
          }
          
          .el-pager {
            li {
              min-width: 28px;
              height: 28px;
              line-height: 28px;
              font-size: 11px;
              margin: 0 1px;
            }
          }
          
          .el-pagination__jump {
            order: 2;
            
            .el-input .el-input__wrapper {
              height: 28px;
              width: 40px;
              font-size: 11px;
            }
          }
        }
      }
    }
  }
}
</style>

